package cn.rtplay.esp32camcar.myView;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import java.util.Objects;

import cn.rtplay.esp32camcar.databinding.DialogAlertLayoutBinding;

public class BackDialog {
    private DialogAlertLayoutBinding mViewBinding;
    private final Context mContext;
    private final AlertDialog mDialog;

    public BackDialog(Context context) {
        this.mContext = context;
        final AlertDialog.Builder layoutDialog = new AlertDialog.Builder(context);
        mDialog = layoutDialog.create();
    }

    public BackDialog Builder() {
        mDialog.show();
        //加载布局并初始化组件
        mViewBinding = DialogAlertLayoutBinding.inflate(LayoutInflater.from(mContext));

        mViewBinding.alertDialogBtnConfirm.setOnClickListener(v -> mOnClickListener.onClick(mContext));
        mViewBinding.alertDialogBtnCancel.setOnClickListener(v -> {
            mOnCancelClickListener.onClick(mContext);
            mDialog.dismiss();
        });

        //在布局文件中设置了背景为圆角的shape后，发现上边显示的是我们的自定义的圆角的布局文件，
        //底下居然还包含了一个方形的白块，如何去掉这个白块,添加下面这句话
        Objects.requireNonNull(mDialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mDialog.getWindow().setContentView(mViewBinding.getRoot());//自定义布局应该在这里添加，要在dialog.show()的后面
        return this;
    }

    public BackDialog setTitleText(String title) {
        mViewBinding.alertDialogText.setText(title);
        return this;
    }

    public BackDialog setConfirmText(String text) {
        mViewBinding.alertDialogBtnConfirm.setText(text);
        return this;
    }

    public BackDialog setCancelText(String text) {
        mViewBinding.alertDialogBtnCancel.setText(text);
        return this;
    }

    public interface OnConfirmClickListener {
        /**
         * Called when a view has been clicked.
         *
         * @param c Context
         */
        void onClick(Context c);
    }

    private OnConfirmClickListener mOnClickListener;

    public BackDialog setOnConfirmClickListener(@Nullable OnConfirmClickListener l) {
        mOnClickListener = l;
        return this;
    }

    public interface OnCancelClickListener {
        /**
         * Called when a view has been clicked.
         *
         * @param c Context
         */
        void onClick(Context c);
    }

    private OnCancelClickListener mOnCancelClickListener;

    public BackDialog setOnCancelClickListener(@Nullable OnCancelClickListener l) {
        mOnCancelClickListener = l;
        return this;
    }
}
